const { Router } = require("express");
const Orders = require("../model/Orders");

const router = new Router();

// router.use(require("../middleware/auth.js"));
// 添加订单
//http://localhost:8000/api/orders/
router.post("/add", async (req, res) => {
  const {
    useid,
    key,
    time,
    paymentMethod,
    productAmount,
    deliveryFee,
    payAmount,
    productQuantity,
    state,
    AddressId,
    appointmentTime,
    orderItem,
  } = req.body;

  const aa = JSON.parse(AddressId);
  const cc = JSON.parse(orderItem);
  console.log(aa, "-----------");
  console.log(cc, "==============");
  const data = await Orders.create({
    useid,
    key,
    time,
    paymentMethod,
    productAmount,
    deliveryFee,
    payAmount,
    productQuantity,
    state,
    AddressId: aa,
    appointmentTime,
    orderItem: cc,
  });

  res.status(200).json({ message: "添加成功", data });
});

//查询所有订单

router.get("/", async (req, res) => {
  // const user = req.userInfo._id;
  // const { _id } = req.query;
  const data = await Orders.find({});
  res.status(200).json({ message: "查询成功", data });
});

// 根据条件查询订单
router.get("/condition", async (req, res) => {
  const { ...list } = req.query;
  const data = await Orders.find({ ...list });
  res.status(200).json({ message: "查询成功", data });
});

//根据订单id查询订单
// 订单id
router.get("/orderId", async (req, res) => {
  // const user = req.userInfo._id;
  const { _id } = req.query;
  const data = await Orders.find({ _id }); //.populate(["AddressId"])
  res.status(200).json({ message: "查询成功", data });
});

//删除订单
router.delete("/", async (req, res) => {
  const { _id } = req.query;
  await Orders.findByIdAndDelete(_id);
  res.status(200).json({ message: "删除成功" });
});

// 修改订单状态
// 修改用户地址信息
router.patch("/", async (req, res) => {
  const { _id, state } = req.body;
  const data = await Orders.findByIdAndUpdate({ _id }, { state });
  res.status(200).json({ message: "修改成功", data });
});

module.exports = router;
